----------- 
-- Author: Bojun Chen
-- Date: 2021-09-14 13:47:40
-- Desc: 状态机控制类
----------- 


local BaseState = BaseState
local FiniteStateMachine = class("FiniteStateMachine", BaseState)

--[[
    @desc: 构造
    author:Bojun Chen
    time:2021-09-14 15:43:19
    --@state: 默认状态实例
    @return:
]]
function FiniteStateMachine:ctor(state)
    self.stateMachineName = 'FiniteStateMachine'
    self.states = {}
    self.isStart = false
    self:AddState(state)
    self.curState = state
end

--[[
    @desc: 添加状态
    author:Bojun Chen
    time:2021-09-14 15:43:10
    --@state: 状态实例
    @return:
]]
function FiniteStateMachine:AddState(state)
    if state == nil then
        LogError('state is nil!')
        return
    end

    local s = self.states[state.name]
    if s ~= nil then
        LogError('the state name' .. state.name .. 'is exist, can not add this state!')
        return
    end

    self.states[state.name] = state
    state:SetStateMachine(self)
end

--[[
    @desc: 移除状态
    author:Bojun Chen
    time:2021-09-14 15:42:57
    --@state: 状态实例
    @return:
]]
function FiniteStateMachine:RemoveState(state)
    if state == nil then
        LogError('state is nil')
        return
    end

    local s = self.states[state.name]
    if s == nil then
        LogInfo('state ' .. state.name .. 'does not exist, can not remove this state!')
        return
    end

    self.states[state.name] = nil
end

--[[
    @desc: 改变状态
    author:Bojun Chen
    time:2021-09-14 15:43:42
    --@nextState: 下一个状态
    @return:
]]
function FiniteStateMachine:ChangeState(nextState)
    if self.curState ~= nil then
        self.curState:OnExit(nextState)
    end

    if nextState == nil then
        return
    end

    self.curState = nextState
    nextState:OnEnter()    
end

--[[
    @desc: 帧更新
    author:Bojun Chen
    time:2021-09-14 15:43:57
    @return:
]]
function FiniteStateMachine:OnUpdate()
    if not self.isStart then return end
    if self.curState ~= nil then
        self.curState:OnUpdate()
    end
end

--[[
    @desc: 通过名字获取状态
    author:Bojun Chen
    time:2021-09-14 15:44:31
    --@stateName: 状态名字
    @return:
]]
function FiniteStateMachine:GetStateByName(stateName)
    if next(self.states) == nil then return nil end

    local s = self.states[stateName]
    return s
end

--[[
    @desc: 状态机开始运行，配置好状态后调用    
    author:Bojun Chen
    time:2021-09-14 15:46:27
    @return:
]]
function FiniteStateMachine:Start()
    if self.curState ~= nil then
        self.curState:OnEnter()
    end

    self.isStart = true
end

--[[
    @desc: 暂停状态机
    author:Bojun Chen
    time:2021-09-14 15:48:41
    @return:
]]
function FiniteStateMachine:Pause()
    self.isStart = false
end

--[[
    @desc: 暂停后继续
    author:Bojun Chen
    time:2021-09-14 15:49:21
    @return:
]]
function FiniteStateMachine:Resume()
    self.isStart = true
end





return  FiniteStateMachine